package com.qf.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author YDW
 * projectName:project2202_4
 * time:2022/6/15 9:12
 * description:
 */
@Component
public class MyGlobalFiter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //判断请求中是否包含token数据
        //获取request中的请求数据
        //exchange 交换机
        ServerHttpRequest request = exchange.getRequest();
        //从请求头中获取数据
//        request.getHeaders().get()
        //从请求参数中获取tonken
        //获取请求中所有的请求参数
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        //获取token数据
        String token = queryParams.getFirst("token");

        //判断是否有token，若果有则放行，登录成功
        if(!StringUtils.isEmpty(token)){
            System.out.println("认证成功，可继续操作");
            return chain.filter(exchange);
        }

        //如果没有登录失败，返回401状态码
        else {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();

        }

    }

    //返回值可以表示 过滤器的执行顺序
    @Override
    public int getOrder() {
        return 0;
    }
}
